"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const qiniu = require("qiniu");
const request = require("request");
const uid = require("uid");
const fs = require("fs");
const path = require("path");
const http = require("http");
const utility_1 = require("./../utility");
// import { Readable, PassThrough } from 'stream'
const ACCESS_KEY = 'hdTc-x9-BbHPheZ1-pCyjWMAf0OJoPVvTj9WTy9G';
const SECRET_KEY = 'Rn7Qdtof27Dg3QX4-JkOuhj3X6LYdkL2DXMU3-y5';
const BUCKET = 'jigi-imgs';
const QINIU_URL = 'https://oe5s738zx.qnssl.com';
qiniu.conf.ACCESS_KEY = ACCESS_KEY;
qiniu.conf.SECRET_KEY = SECRET_KEY;
var options = { scope: BUCKET };
var mac = new qiniu.auth.digest.Mac(qiniu.conf.ACCESS_KEY, qiniu.conf.SECRET_KEY);
var putPolicy = new qiniu.rs.PutPolicy(options);
var uploadToken = putPolicy.uploadToken(mac);
let qConfig = new qiniu.conf.Config();
var formUploader = new qiniu.form_up.FormUploader(qConfig);
var putExtra = new qiniu.form_up.PutExtra();
var bucketManager = new qiniu.rs.BucketManager(mac, qConfig);
function copyImagesFromSkyToQiniu(imageList) {
    return __awaiter(this, void 0, void 0, function* () {
        if (!imageList || !Array.isArray(imageList) || !imageList.length)
            return [];
        var results = [];
        let set = new Set(imageList);
        imageList = Array.from(set); //去重
        console.time('上传图片并压缩');
        for (let url of imageList) {
            let newUrl = url;
            try {
                newUrl = yield upload(url);
            }
            catch (error) {
                console.log(`Error occurs when convert image to Qiniu ${JSON.stringify(error)}`);
            }
            results.push(newUrl);
            yield utility_1.delay(800);
        }
        console.timeEnd('上传图片并压缩');
        return results;
    });
}
exports.copyImagesFromSkyToQiniu = copyImagesFromSkyToQiniu;
function upload(skyUrl) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            let res = yield uploadImage(skyUrl);
            if (!res)
                return skyUrl;
            let key = res;
            let newKey = `q_50_${key}`;
            yield compressImage(key, newKey);
            yield deleteImageAfterOneDay(newKey);
            return `${QINIU_URL}/${newKey}`;
        }
        catch (error) {
            return skyUrl;
        }
    });
}
exports.upload = upload;
/** 从顺凯的服务器拉图片，上传到七牛去
 * @param {string}  skyUrl - 顺凯的地址
 */
function uploadImage(skyUrl) {
    return __awaiter(this, void 0, void 0, function* () {
        skyUrl = encodeURI(skyUrl);
        try {
            return new Promise((resolve) => {
                let key = uid(20) + '.jpg';
                let imgPath = path.join(__dirname, './../../temp/' + key);
                let stream = fs.createWriteStream(imgPath);
                stream.on('close', function () {
                    formUploader.putFile(uploadToken, key, imgPath, putExtra, function (respErr, respBody, respInfo) {
                        if (respInfo.statusCode == 200) {
                            console.log('upload success');
                            resolve(key);
                        }
                        else {
                            console.log('upload fail');
                            resolve(false);
                        }
                    });
                });
                request(skyUrl).pipe(stream);
            });
        }
        catch (error) {
            console.log(`error happen at uploadImage function ${JSON.stringify(error)}`);
            return false;
        }
    });
}
exports.uploadImage = uploadImage;
/** 压缩图片 */
function compressImage(key, newKey) {
    return __awaiter(this, void 0, void 0, function* () {
        return new Promise((resolve, reject) => {
            try {
                var bucket = BUCKET;
                var host = BUCKET + ".qiniudn.com";
                // jigi-imgs.qiniudn.com
                var encodedEntryURI = qiniu.util.urlsafeBase64Encode(bucket + ":" + newKey);
                var signingStr = "/" + key + "?imageView2/3/w/1200/h/900/q/50|saveas/" + encodedEntryURI;
                var savePath = BUCKET + ".qiniudn.com/" + key + "?imageView2/3/w/1200/h/900/q/50|saveas/" + encodedEntryURI;
                var signed = qiniu.util.hmacSha1(new Buffer(savePath), SECRET_KEY);
                var signedSafe1 = qiniu.util.base64ToUrlSafe(signed);
                var imgUrl = signingStr + "/sign/" + ACCESS_KEY + ":" + signedSafe1;
                let req = http.get({ host: host, port: 80, path: imgUrl, timeout: 3000 }, function (res) {
                    res.setEncoding('UTF-8');
                    res.on('data', function (data) { });
                    res.on('end', function () {
                        console.log(`压缩结束: ${newKey}`);
                        resolve(); //结束
                    });
                    res.on('error', err => {
                        console.log(`${newKey} 压缩出错${JSON.stringify(err)}`);
                        reject(err);
                    });
                });
                req.on('error', (err) => {
                    reject(`压缩出错 request error ${JSON.stringify(err)}`);
                });
            }
            catch (error) {
                reject(`压缩出错 compressImage: something unknown happened ${JSON.stringify(error)}`);
            }
        });
    });
}
exports.compressImage = compressImage;
function deleteImageAfterOneDay(key) {
    return __awaiter(this, void 0, void 0, function* () {
        return new Promise((resolve, reject) => {
            bucketManager.deleteAfterDays(BUCKET, key, 1, function (err, respBody, respInfo) {
                if (err)
                    reject(err);
                console.log('删除结束');
                resolve();
            });
        });
    });
}
exports.deleteImageAfterOneDay = deleteImageAfterOneDay;
